const { Sequelize } = require('sequelize');

// 创建 Sequelize 实例
const sequelize = new Sequelize(
    process.env.DB_NAME,
    process.env.DB_USER,
    process.env.DB_PASS,
    {
        host: process.env.DB_HOST,
        port: process.env.DB_PORT,
        dialect: 'mysql',
        logging: process.env.NODE_ENV === 'development' ? console.log : false,
        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        }
    }
);

// 导出sequelize实例和连接数据库的函数
module.exports = {
    sequelize,
    connectDB: async () => {
        try {
            await sequelize.authenticate();
            console.log('Database connection has been established successfully.');
            
            // 同步模型到数据库（开发环境下可以使用）
            // 使用alter: true来修改表结构而不是重建，避免数据丢失
            await sequelize.sync({ alter: true });
            console.log('Models synchronized with database.');
            
            return sequelize;
        } catch (error) {
            console.error('Unable to connect to the database:', error);
            throw error;
        }
    }
};